package com.night.book.util;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.drawable.StateListDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.night.book.ui.MyApplication;

public class ViewUtil {
	public static View inflateView(int redId, ViewGroup parent) {
		View view = LayoutInflater.from(parent.getContext()).inflate(redId,
				parent, false);
		return view;
	}

	/**
	 * 通过制定的 layout xml 生成一个view
	 * 
	 * @param redId
	 *            layout的id
	 * @param context
	 * @return
	 */
	public static View inflateView(int redId, Context context) {
		View view = LayoutInflater.from(context).inflate(redId, null, false);
		return view;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(float dpValue) {
		final float scale = MyApplication.getContext().getResources()
				.getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(float pxValue) {
		final float scale = MyApplication.getContext().getResources()
				.getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static ColorStateList createColorStateList(int normal, int pressed) {
		ColorStateList myColorStateList = new ColorStateList(new int[][] {
				new int[] { android.R.attr.state_pressed },
				new int[] { android.R.attr.state_focused },
				new int[] { android.R.attr.state_checked },
				new int[] { -android.R.attr.state_enabled },
				new int[] { android.R.attr.state_enabled } // state
				}, new int[] { pressed, pressed, pressed, normal, normal });
		return myColorStateList;
	}

	public static StateListDrawable createStateListDrawable(int normal,
			int pressed) {
		Resources resources = MyApplication.getContext().getResources();
		StateListDrawable mStateListDrawable = new StateListDrawable();
		mStateListDrawable.addState(new int[] { android.R.attr.state_pressed },
				resources.getDrawable(pressed));
		mStateListDrawable.addState(new int[] { android.R.attr.state_focused },
				resources.getDrawable(pressed));
		mStateListDrawable.addState(new int[] { android.R.attr.state_checked },
				resources.getDrawable(pressed));
		mStateListDrawable.addState(
				new int[] { -android.R.attr.state_enabled },
				resources.getDrawable(pressed));
		mStateListDrawable.addState(new int[] { android.R.attr.state_enabled },
				resources.getDrawable(normal));
		return mStateListDrawable;
	}
}
